<template>
  <div class="app-container">
    <!-- 表格 -->
    <vxe-grid ref="xGridDom" v-bind="xGridOpt">
      <!-- 左侧按钮列表 -->
      <template #toolbar-btns>
        <vxe-button status="primary" icon="vxe-icon-add" @click="crudStore.onShowModal()">新增人员</vxe-button>
      </template>

      <!-- 操作 -->
      <template #row-operate="{ row }">
        <el-tooltip class="box-item" effect="dark" content="编辑" placement="top-end">
          <el-button link icon="Edit" type="primary" @click="crudStore.onShowModal(row)"/>
        </el-tooltip>
        <!--        先不支持人员删除，其他表有用到人员表的id-->
        <!--        <el-tooltip class="box-item" effect="dark" content="删除" placement="top-end">-->
        <!--          <el-button link icon="Delete" type="danger" @click="crudStore.onDelete(row)"/>-->
        <!--        </el-tooltip>-->
      </template>
    </vxe-grid>
    <!-- 弹窗 -->
    <vxe-modal ref="xModalDom" v-bind="xModalOpt">
      <!-- 表单 -->
      <vxe-form ref="xFormDom" v-bind="xFormOpt"></vxe-form>
    </vxe-modal>
  </div>
</template>

<script lang="ts" setup>
import {nextTick, reactive, ref} from "vue"
import {type ElMessageBoxOptions, ElMessageBox, ElMessage} from "element-plus"
import {formatDateTime, trimValue} from "@/utils/index"

import {
  type VxeGridInstance,
  type VxeGridProps,
  type VxeModalInstance,
  type VxeModalProps,
  type VxeFormInstance,
  type VxeFormProps,
  type VxeGridPropTypes,
  type VxeFormDefines
} from "vxe-table"

import {
  addPeopleApi,
  deletePeopleApi,
  PeopleTableData,
  getPeopleApi, RowMeta,
  updatePeopleApi
} from "@/api/customer/people"
import {jobTitleOption, statusOption} from "@/views/customer/people/dict";

defineOptions({
  name: "People"
})

//#region vxe-grid
const xGridDom = ref<VxeGridInstance>()
const xGridOpt: VxeGridProps = reactive({
  loading: true,
  autoResize: true,
  /** 分页配置项 */
  pagerConfig: {
    align: "right"
  },
  /** 表单配置项 */
  formConfig: {
    items: [
      {
        field: "name",
        itemRender: {
          name: "$input",
          props: {placeholder: "姓名", clearable: true}
        }
      },
      {
        itemRender: {
          name: "$buttons",
          children: [
            {
              props: {type: "submit", content: "搜索", status: "primary"}
            }
          ]
        }
      }
    ]
  },
  /** 工具栏配置 */
  toolbarConfig: {
    refresh: true,
    custom: false,
    slots: {buttons: "toolbar-btns"}
  },
  /** 列配置 */
  columns: [
    {
      field: "id",
      title: "ID",
      width: "100px"
    },
    {
      field: "name",
      title: "姓名",
    },
    {
      field: "jobTitle",
      title: "职位",
      formatter: ({row}) => {
        switch (row.jobTitle) {
          case 1:
            return "交付"
          case 2:
            return "销售"
          case 3:
            return "研发"
          case 4:
            return "售后"
          case 5:
            return "运维"
          case 6:
            return "产品"
          case 7:
            return "售前"
        }
      }
    },
    {
      field: "status",
      title: "状态",
      formatter: ({row}) => {
        switch (row.status) {
          case 1:
            return "在职"
          case 2:
            return "离职"
        }
      }
    },
    {
      field: "updatedAt",
      sortable: true,
      title: "更新时间",
      formatter: (params) => {
        return formatDateTime(params.row.updatedAt)
      }
    },
    {
      title: "操作",
      width: "250px",
      fixed: "right",
      showOverflow: false,
      slots: {default: "row-operate"}
    }
  ],
  /** 数据代理配置项（基于 Promise API） */
  proxyConfig: {
    /** 启用动态序号代理 */
    seq: true,
    /** 是否代理表单 */
    form: true,
    /** 是否自动加载，默认为 true */
    // autoLoad: false,
    props: {
      total: "total"
    },
    ajax: {
      query: ({page, form}: VxeGridPropTypes.ProxyAjaxQueryParams) => {
        xGridOpt.loading = true
        crudStore.clearTable()
        return new Promise<any>((resolve: Function) => {
          let total = 0
          let result: RowMeta[] = []
          /** 加载数据 */
          const callback = (res: PeopleTableData) => {
            if (res && res.data) {
              const resData = res.data
              // 总数
              if (Number.isInteger(resData.total)) {
                total = resData.total
              }
              // 分页数据
              if (Array.isArray(resData.list)) {
                result = resData.list
              }
            }
            xGridOpt.loading = false
            resolve({total, result})
          }
          /** 接口需要的参数 */
          const params = {
            name: trimValue(form.name),
            size: page.pageSize,
            currentPage: page.currentPage
          }
          /** 调用接口 */
          getPeopleApi(params).then(callback).catch(callback)
        })
      }
    }
  }
})
//#endregion

//#region vxe-modal
const xModalDom = ref<VxeModalInstance>()
const xModalOpt: VxeModalProps = reactive({
  title: "",
  width: "350px",
  height: "280px",
  showClose: true,
  escClosable: true,
  maskClosable: false,
  beforeHideMethod: () => {
    xFormDom.value?.clearValidate()
    return Promise.resolve()
  }
})
//#endregion

//#region vxe-form
const xFormDom = ref<VxeFormInstance>()
const xFormOpt = reactive<VxeFormProps>({
  span: 20,
  titleWidth: "30%",
  loading: false,
  /** 是否显示标题冒号 */
  titleColon: false,
  titleAlign: "right",
  /** 表单数据 */
  data: {
    id: "",
    name: "",
    jobTitle: "",
    status: 1
  },
  /** 项列表 */
  items: [
    {
      field: "name",
      title: "姓名",
      itemRender: {
        name: "$input",
        props: {
          placeholder: "请输入",
          clearable: true
        }
      }
    },
    {
      field: "jobTitle",
      title: "职位",
      itemRender: {
        name: "$select",
        props: {
          placeholder: "请选择",
          options: jobTitleOption,
        }
      }
    },
    {
      field: "status",
      title: "状态",
      itemRender: {
        name: "$radio",
        options: statusOption
      }
    },
    {
      align: "right",
      itemRender: {
        name: "$buttons",
        children: [
          {props: {content: "取消"}, events: {click: () => xModalDom.value?.close()}},
          {
            props: {type: "submit", content: "确定", status: "primary"},
            events: {click: () => crudStore.onSubmitForm()}
          }
        ]
      }
    }
  ],
  /** 校验规则 */
  rules: {
    name: [
      {
        required: true,
        validator: ({itemValue}) => {
          if (itemValue === "") {
            return new Error("请输入姓名")
          }
        }
      }
    ],
    jobTitle: [
      {
        required: true,
        validator: ({itemValue}) => {
          if (itemValue === "") {
            return new Error("请选择职位")
          }
        }
      }
    ]
  }
})
//#endregion

//#region CRUD
const crudStore = reactive({
  /** 表单类型：修改：true 新增：false */
  isUpdate: true,
  /** 加载表格数据 */
  commitQuery: () => xGridDom.value?.commitProxy("query"),
  /** 清空表格数据 */
  clearTable: () => xGridDom.value?.reloadData([]),
  /** 点击显示弹窗 */
  onShowModal: (row?: RowMeta) => {
    if (row) {
      crudStore.isUpdate = true
      xModalOpt.title = "编辑人员"
      // 赋值
      xFormOpt.data.id = row.id
      xFormOpt.data.name = row.name
      xFormOpt.data.jobTitle = row.jobTitle
      xFormOpt.data.status = row.status
    } else {
      xFormOpt.data.id = 0
      crudStore.isUpdate = false
      xModalOpt.title = "新增人员"
    }
    xModalDom.value?.open()
    nextTick(() => {
      !crudStore.isUpdate && xFormDom.value?.reset()
      xFormDom.value?.clearValidate()
    })
  },
  /** 确定并保存 */
  onSubmitForm: () => {
    if (xFormOpt.loading) return
    xFormDom.value?.validate(async (errMap?: VxeFormDefines.ValidateErrorMapParams) => {
      if (errMap) return
      xFormOpt.loading = true
      const callback = (err?: any) => {
        xFormOpt.loading = false
        if (err) return
        xModalDom.value?.close()
        !crudStore.isUpdate && crudStore.afterInsert()
        crudStore.commitQuery()
      }
      try {
        let apiFunction
        if (crudStore.isUpdate) {
          apiFunction = updatePeopleApi
        } else {
          apiFunction = addPeopleApi
        }

        const res = await apiFunction({
          id: xFormOpt.data.id,
          name: xFormOpt.data.name,
          jobTitle: xFormOpt.data.jobTitle,
          status: xFormOpt.data.status
        })
        ElMessage({type: "success", message: res.msg})
      } catch (error) {
        console.log(error)
      } finally {
        callback()
      }
    })
  },

  /** 新增后是否跳入最后一页 */
  afterInsert: () => {
    const pager: VxeGridPropTypes.ProxyAjaxQueryPageParams | undefined = xGridDom.value?.getProxyInfo()?.pager
    if (pager) {
      const currTotal: number = pager.currentPage * pager.pageSize
      if (currTotal === pager.total) {
        ++pager.currentPage
      }
    }
  },
  /** 删除 */
  onDelete: (row: RowMeta) => {
    const tip = `确定 <strong style='color:red;'>删除</strong> 人员 <strong style='color:#409eff;'>${row.name}</strong> ？`
    const config: ElMessageBoxOptions = {
      type: "warning",
      showClose: true,
      closeOnClickModal: true,
      closeOnPressEscape: true,
      cancelButtonText: "取消",
      confirmButtonText: "确定",
      dangerouslyUseHTMLString: true
    }
    ElMessageBox.confirm(tip, "提示", config)
      .then(() => {
        deletePeopleApi(row.id)
          .then(() => {
            ElMessage.success("删除成功")
            crudStore.afterDelete()
            crudStore.commitQuery()
          })
          .catch(() => 1)
      })
      .catch(() => 1)
  },
  /** 删除后是否返回上一页 */
  afterDelete: () => {
    const tableData: RowMeta[] = xGridDom.value!.getData()
    const pager: VxeGridPropTypes.ProxyAjaxQueryPageParams | undefined = xGridDom.value?.getProxyInfo()?.pager
    if (pager && pager.currentPage > 1 && tableData.length === 1) {
      --pager.currentPage
    }
  }
})
//#endregion
</script>

<style lang="scss" scoped>
.expand-wrapper {
  padding: 10px;
}

.tooltip-content {
  white-space: pre-wrap; /* 或者使用 pre-line */
  word-break: break-all; /* 根据需要使用 word-break 属性 */
}
</style>
